import { message } from 'antd'
import services from '@/services'
import type { Words } from '@/services/resources/words-library'

export function useEditWords() {
  const [editing, setEditing] = useState<null | true | Words>(null)
  const edit = useCallback((words?: Words) => setEditing(words ?? true), [])
  const finishEdit = useCallback(() => setEditing(null), [])

  const remove = useCallback(async (id: number) => services.resources.wordsLibrary.remove(id), [])

  return {
    editing,
    edit,
    finishEdit,
    remove,
  }
}

export function useSendWords() {
  const executeSend = useCallback(async (words: Words) => {
    const sended = await services.resources.wordsLibrary.send(words.items)
    if (sended) void message.success('发送成功')
    else void message.warning('发送失败：没有当前联系人')
  }, [])

  const [confirming, setConfirming] = useState<Words | null>(null)
  const confirmed = useCallback(
    (edited: Words) => {
      setConfirming(null)
      void executeSend(edited)
    },
    [executeSend],
  )
  const cancelConfirm = useCallback(() => setConfirming(null), [])

  const _send = (words: Words, needConfirm = true) => {
    if (needConfirm) setConfirming(words)
    else void executeSend(words)
  }
  const send = useCallback(_send, [executeSend])

  return {
    send,
    confirming,
    confirmed,
    cancelConfirm,
  }
}
